package com.acane.instagram.feature.post

import android.annotation.SuppressLint
import android.util.Log
import android.widget.Toast
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.ClickableText
import androidx.compose.material.Divider
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.MaterialTheme
import androidx.compose.material.ModalBottomSheetLayout
import androidx.compose.material.ModalBottomSheetValue
import androidx.compose.material.TextField
import androidx.compose.material.TextFieldDefaults
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.rememberModalBottomSheetState
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavController
import coil.compose.AsyncImage
import com.acane.instagram.R
import com.acane.instagram.core.config.Config
import com.acane.instagram.core.design.theme.InstagramBlue
import com.acane.instagram.core.design.theme.InstagramDarkGray
import com.acane.instagram.core.design.theme.InstagramLightGray
import com.acane.instagram.core.extension.clickableNoRipple
import com.acane.instagram.core.model.PostInfo
import com.acane.instagram.core.model.UserInfo
import com.acane.instagram.core.model.dto.CommentDTO
import com.acane.instagram.core.model.network.datasource.MyRetrofitDatasource
import com.acane.instagram.feature.common.SessionManager
import com.acane.instagram.feature.home.CommentList
import com.acane.instagram.feature.home.HandleVideoPlayback
import com.acane.instagram.feature.home.HomeViewModel
import com.acane.instagram.feature.home.ImageCarousel
import com.acane.instagram.feature.notification.NotificationViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

@SuppressLint(
    "UnusedMaterial3ScaffoldPaddingParameter", "StateFlowValueCalledInComposition",
    "CoroutineCreationDuringComposition"
)
@OptIn(ExperimentalMaterial3Api::class, ExperimentalMaterialApi::class)
@Composable
fun UserPostList(
    navController: NavController,
    toProfile: (String) -> Unit,
    viewModel: PostViewModel = viewModel(),
    userId: String?,
    postPosition: Int,
    homeViewModel: HomeViewModel = viewModel(),
    notificationViewModel: NotificationViewModel = viewModel(),

    ) {
    val postId by homeViewModel.postId.collectAsState(initial = null) // 监听 postId 的变化
    var currentVisibleVideoIndex by remember { mutableIntStateOf(-1) } // 定义当前播放的视频索引
    val postInfoList = viewModel.postDatum.value

    LaunchedEffect(userId) {
        viewModel.initPostData(userId)
    }

    val listState = rememberLazyListState()

    val coroutineScope = rememberCoroutineScope()
    val isFollowing by homeViewModel.isFollowing.collectAsState(initial = false)

    //val (isFollowing, setIsFollowing) = remember { mutableStateOf(false) }
    val scope = rememberCoroutineScope()
    // 加载关注状态
    LaunchedEffect(Unit) {
        coroutineScope.launch(Dispatchers.IO) {
            val isFollowingResponse =
                homeViewModel.judgeIsFollowed(userId!!, SessionManager.currentUser?.id)
            Log.d("UserPostList", "发送请求获得的isFollowingResponse: $isFollowingResponse")
            //setIsFollowing(isFollowingResponse)
            homeViewModel.updateIsFollowing(isFollowingResponse)
        }
    }

    // 数据加载完成后定位
    LaunchedEffect(postInfoList.isNotEmpty()) {
        if (postInfoList.isNotEmpty() && postPosition < postInfoList.size) {
            listState.animateScrollToItem(
                index = postPosition,
                scrollOffset = 0
            )
        }
    }

    val commentBottomSheetState =
        rememberModalBottomSheetState(initialValue = ModalBottomSheetValue.Hidden)


    var selectedPostUser by remember { mutableStateOf<UserInfo?>(null) }

    val commentNotification = notificationViewModel.commentNotification.collectAsState()
    val commentDatum = commentNotification.value
// 添加状态变量来跟踪回复的评论
    var replyToComment by remember { mutableStateOf<CommentDTO?>(null) }

    ModalBottomSheetLayout(
        sheetState = commentBottomSheetState,
        sheetShape = RoundedCornerShape(topStart = 10.dp, topEnd = 10.dp),
        sheetContent = {
            val comments by homeViewModel.comments.collectAsState()
            val commentData = comments.filter { it.postId == postId }

            //val commentData = commentDatum.filter { it?.postId == selectedPostId }
            Log.d("UserPostList", "选中的帖子ID：${postId}")
            Log.d("UserPostList", "用户帖子列表页面的commentDatum: $commentDatum")
            Log.d("UserPostList", "筛选后的用户帖子列表页面的commentDatum: $commentData")

            val focusRequester = remember { FocusRequester() }

            if (commentData.isEmpty()) {
                LazyColumn(
                    modifier = Modifier
                        .fillMaxSize()
                        .weight(1f),
                    horizontalAlignment = Alignment.CenterHorizontally,
                ) {
                    item {
                        Box(
                            modifier = Modifier
                                .fillMaxWidth()
                                .wrapContentSize(align = Alignment.TopCenter)

                        ) {
                            Image(
                                painter = painterResource(id = R.drawable.bar_horizontal),
                                contentDescription = "bar",
                            )
                        }
                    }
                    item {
                        androidx.compose.material.Text(
                            text = "还没有评论",
                            modifier = Modifier.padding(16.dp),
                            fontSize = 16.sp,
                            fontWeight = FontWeight.Bold,
                        )
                        androidx.compose.material.Text(
                            text = "发起对话。",
                            fontSize = 12.sp,
                            color = InstagramDarkGray
                        )
                    }
                }
                UserCommentBar(
                    postViewModel = viewModel,
                    onSendComment = {
                        val newComment = postId?.let {
                            CommentDTO(
                                id = "",
                                commenterId = SessionManager.currentUser?.id!!,
                                postId = it,
                                content = viewModel.caption,
                                timestamp = "",
                                likes = 0,
                                parentId = replyToComment?.id ?: "",
                            )
                        }
                        newComment?.let { homeViewModel.sendComment(it) }

                        postId?.let {
                            notificationViewModel.sendMessageNotification(
                                commenterId = SessionManager.currentUser?.id!!,
                                postId = it,
                                content = viewModel.caption,
                            )
                        }
                        Log.d("HomeRoute", "🟢 发送评论：${viewModel.caption}")
                        viewModel.caption = ""
                    },
                    replyToComment = replyToComment,
                    focusRequester = focusRequester
                )

            } else {
                LazyColumn(
                    modifier = Modifier
                        .fillMaxWidth()
                        .weight(1f)
                ) {
                    // 添加 Bar
                    item {
                        Box(
                            modifier = Modifier
                                .fillMaxWidth()
                                .wrapContentSize(align = Alignment.Center)
                        ) {
                            Image(
                                painter = painterResource(id = R.drawable.bar_horizontal),
                                contentDescription = "bar",
                            )
                        }
                    }
                    // 标题区域
                    item {
                        Row(
                            modifier = Modifier.fillMaxWidth(), // 添加宽度约束
                            horizontalArrangement = Arrangement.Center
                        ) {
                            androidx.compose.material3.Text(
                                text = "评论",
                                fontWeight = FontWeight.Bold,
                                fontSize = 12.sp
                            )
                        }
                    }
                    // 分割线
                    item {
                        Divider(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(vertical = 2.dp)
                        )
                    }
                    // 评论区域
                    item {
                        val groupedComments = commentData.groupBy {
                            when {
                                it.parentId.isNullOrEmpty() -> "root"
                                else -> it.parentId
                            }
                        }
                        selectedPostUser?.let {
                            CommentList(
                                comments = groupedComments["root"] ?: emptyList(),
                                groupedComments = groupedComments,
                                onReplyClick = { replyToComment = it },
                                notificationViewModel = notificationViewModel,
                                homeViewModel = homeViewModel,
                                scope = coroutineScope,
                                selectedPostUser = it,
                                toProfile = toProfile,
                                commentBottomSheetState = commentBottomSheetState,
                                focusRequester = focusRequester,
                            )
                        }
                    }

                }
                UserCommentBar(
                    postViewModel = viewModel,
                    onSendComment = {
                        val newComment = postId?.let {
                            CommentDTO(
                                id = "",
                                commenterId = SessionManager.currentUser?.id!!,
                                postId = it,
                                content = viewModel.caption,
                                timestamp = "",
                                likes = 0,
                                parentId = replyToComment?.id ?: "",
                            )
                        }
                        newComment?.let { homeViewModel.sendComment(it) }

                        postId?.let {
                            notificationViewModel.sendMessageNotification(
                                commenterId = SessionManager.currentUser?.id!!,
                                postId = it,
                                content = viewModel.caption,
                            )
                        }
                        Log.d("HomeRoute", "🟢 发送评论：${viewModel.caption}")
                        viewModel.caption = ""
                        replyToComment = null
                    },
                    replyToComment = replyToComment,
                    focusRequester = focusRequester
                )
            }

        }
    ) {
        Scaffold(
            topBar = {
                TopAppBar(
                    navigationIcon = {
                        IconButton(onClick = {
                            navController.popBackStack()
                        }) {
                            Icon(Icons.Default.ArrowBack, null)
                        }
                    },
                    title = {
                        Text("帖子")
                    },
                    actions = {
                        Log.d("UserPostList", "当前帖子主人id: $userId")
                        Log.d("UserPostList", "当前isFollow值：${isFollowing}")
                        if (userId == SessionManager.currentUser?.id) {
                            // 不能关注自己
                        } else {
                            // 关注按钮
                            Text(
                                text = if (isFollowing) "已关注" else "关注",
                                modifier = Modifier
                                    .padding(end = 16.dp)
                                    .clickable {
                                        Log.d("UserPostList", "当前isFollowing: $isFollowing")
                                        Log.d("UserPostList", "当前userId: $userId")

                                        if (isFollowing) {
                                            // scope.launch(Dispatchers.IO) {
                                            try {
                                                homeViewModel.sendUnFollowRequest(
                                                    followingId = userId!!,
                                                    followerId = SessionManager.currentUser?.id!!
                                                )
                                                homeViewModel.updateIsFollowing(false)
                                            } catch (e: Exception) {
                                                Log.e(
                                                    "UserPostList",
                                                    "请求失败: ${e.message}",
                                                    e
                                                )
                                            }
                                            // }
                                        } else {
                                            //scope.launch(Dispatchers.IO) {
                                            homeViewModel.sendFollowRequest(
                                                followingId = userId!!,
                                                followerId = SessionManager.currentUser?.id!!
                                            )
                                            homeViewModel.updateIsFollowing(true)
                                            //}
                                        }

                                    },
                                style = TextStyle(
                                    fontSize = 14.sp,
                                    fontWeight = FontWeight.Bold,
                                    color = InstagramBlue
                                )
                            )
                        }
                    },
                    colors = TopAppBarDefaults.topAppBarColors(
                        containerColor = Color.White
                    ),
                )
            },
            containerColor = Color.White,
        ) { padding ->
            // 推荐用户列表
            LazyColumn(
                state = listState,
                modifier = Modifier
                    .fillMaxSize()
                    .padding(padding),
                verticalArrangement = Arrangement.spacedBy(16.dp)
            ) {
                // 推荐帖子列表
                postInfoList.forEachIndexed { index, post ->
                    item {
                        UserPostItem(
                            postInfo = post,
                            toProfile = toProfile,
                            isAutoPlay = currentVisibleVideoIndex == index, // 传递播放状态,
                            onCommentClick = {
                                scope.launch {
                                    homeViewModel.updatePostId(post.id)
                                    homeViewModel.loadComments(post.id)
                                    selectedPostUser = post.user
                                    commentBottomSheetState.show()
                                }
                            }
                        )
                    }
                }
            }
        }
    }


    // 添加滚动监听
    HandleVideoPlayback(listState, postInfoList, currentVisibleVideoIndex) { index ->
        currentVisibleVideoIndex = index // 更新当前播放的索引
    }
}

@OptIn(ExperimentalMaterialApi::class)
@Composable
fun UserPostItem(
    postInfo: PostInfo,
    toProfile: (String) -> Unit,
    isAutoPlay: Boolean, // 新增参数
    homeViewModel: HomeViewModel = viewModel(),
    onCommentClick: () -> Unit,
) {
    val context = LocalContext.current
    val (isLiked, setIsLiked) = remember { mutableStateOf(false) }
    val (isCollected, setIsCollected) = remember { mutableStateOf(false) }
    var likes by remember { mutableStateOf(postInfo.likeCount) }
    var isExpanded by remember { mutableStateOf(false) } // 添加展开状态
    val notificationViewModel: NotificationViewModel = viewModel()
    val scope = rememberCoroutineScope()
    LaunchedEffect(Unit) { // 使用 Unit 确保只执行一次
        scope.launch(Dispatchers.IO) {
            val isLikedResponse = MyRetrofitDatasource.judgeIsLiked(
                postInfo.id,
                SessionManager.currentUser?.id
            ).data == true

            setIsLiked(isLikedResponse)
            Log.d("HomeRoute", "🟢 初始化点赞状态：$isLikedResponse")
        }
    }
    // 初始化收藏状态
    LaunchedEffect(Unit) { // 使用 Unit 确保只执行一次
        scope.launch(Dispatchers.IO) {
            val isCollectedResponse = MyRetrofitDatasource.judgeIsCollected(
                postInfo.id,
                SessionManager.currentUser?.id
            ).data == true

            setIsCollected(isCollectedResponse)
            Log.d("HomeRoute", "🟢 初始化收藏状态：$isCollectedResponse")
        }
    }
    LaunchedEffect(Unit) {
        scope.launch(Dispatchers.IO) {
            val isFollowingResponse = MyRetrofitDatasource.judgeIsFollowed(
                postInfo.user.id!!,
                SessionManager.currentUser?.id
            ).data == true
            //homeViewModel.setIsFollowing(isFollowingResponse)
            homeViewModel.setIsFollowing(postInfo.user.id, isFollowingResponse)
        }
    }

    Column(
        modifier = Modifier
            .padding(vertical = 8.dp),
        horizontalAlignment = Alignment.Start
    ) {
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically
        ) {
            Row(
                verticalAlignment = Alignment.CenterVertically
            ) {
                Spacer(modifier = Modifier.size(8.dp))
                //发布者头像
                AsyncImage(
                    model = postInfo.user.avatar?.let {
                        val url = "${Config.ADDRESS}avatars/$it"
                        Log.d("HomeRoute", "🟢 尝试加载头像 URL: $url")
                        url
                    } ?: run {
                        Log.d("HomeRoute", "🔴 无服务器头像文件名，显示默认头像")
                        R.drawable.ic_default_avatar
                    },
                    contentDescription = "发布者头像",
                    modifier = Modifier
                        .size(30.dp)
                        .clip(CircleShape)
                        .background(Color.Transparent)
                        .clickableNoRipple {
                            postInfo.user.id?.let { toProfile(it) }
                        },
                    contentScale = ContentScale.Crop,
                    error = painterResource(id = R.drawable.ic_default_avatar) // 加载失败时显示默认
                )
                Spacer(modifier = Modifier.width(8.dp)) // 添加左右间距
                //昵称
                postInfo.user.nickName?.let {
                    androidx.compose.material.Text(
                        text = it,
                        fontSize = 14.sp,
                        fontWeight = FontWeight.Bold,
                        color = Color.Black
                    )
                }
                Spacer(modifier = Modifier.weight(1.0f)) // 添加左右间距

            }
            Image(
                painter = painterResource(id = R.drawable.options_vertical),
                contentDescription = "options",
                modifier = Modifier.size(24.dp)
            )
        }

    }
    Spacer(modifier = Modifier.height(8.dp)) // 添加左右间距
    ImageCarousel(
        postInfo = postInfo,
        isLiked = isLiked,
        onLikeClick = {
            val newIsLiked = !isLiked // 先计算新状态
            setIsLiked(newIsLiked)    // 立即更新本地状态

            if (newIsLiked) {         // 根据新状态执行操作
                likes += 1
                scope.launch {
                    MyRetrofitDatasource.likePost(postInfo.id)
                    notificationViewModel.sendLikeNotification(
                        SessionManager.currentUser?.id!!,
                        postInfo.id
                    )
                }
            } else {
                likes -= 1
                scope.launch {
                    MyRetrofitDatasource.unlikePost(postInfo.id)
                }
            }
        },
        isAutoPlay = isAutoPlay,
        onCommentClick = onCommentClick,
        isCollected = isCollected,
        onCollectClick = {
            val newIsCollected = !isCollected // 先计算新状态
            setIsCollected(newIsCollected)
            if (newIsCollected) {
                scope.launch {
                    MyRetrofitDatasource.collectPost(postInfo.id, SessionManager.currentUser?.id!!)
                    // 提示收藏成功
                    Toast.makeText(context, "收藏成功", Toast.LENGTH_SHORT).show()
                }
            } else {
                scope.launch {
                    MyRetrofitDatasource.unCollectPost(postInfo.id, SessionManager.currentUser?.id!!)
                    // 提示取消收藏
                    Toast.makeText(context, "取消收藏", Toast.LENGTH_SHORT).show()
                }
            }
        }
    )
    Spacer(modifier = Modifier.height(6.dp)) // 添加底部内边距
    //点赞量
    Text(
        text = "${likes}次赞",
        fontSize = 12.sp,
        modifier = Modifier.padding(start = 8.dp)
    )
    Spacer(modifier = Modifier.height(6.dp)) // 添加底部内边距
    //文案
    ClickableText(
        text = buildAnnotatedString {
            val text = if (isExpanded) postInfo.content else "${postInfo.content?.take(50)}...展开"
            append(text)
            if (!isExpanded) {
                text?.let {
                    addStyle(
                        style = SpanStyle(color = InstagramDarkGray),
                        start = text.length - 3,
                        end = it.length
                    )
                }
            }
        },
        style = TextStyle(fontSize = 12.sp),
        modifier = Modifier
            .padding(start = 8.dp)
            .clickable { isExpanded = !isExpanded }, // 添加 onClick 回调
        overflow = TextOverflow.Ellipsis,
        maxLines = if (isExpanded) Int.MAX_VALUE else 2, // 设置 maxLines
        onClick = { isExpanded = !isExpanded } // 添加 onClick 回调
    )
    Spacer(modifier = Modifier.height(6.dp)) // 添加底部内边距
    //评论量
    Text(
        text = "共${postInfo.commentCount}条评论",
        fontSize = 12.sp,
        color = InstagramDarkGray,
        modifier = Modifier.padding(start = 8.dp)
    )
    Spacer(modifier = Modifier.height(6.dp)) // 添加底部内边距
    //头像 + ”添加评论“
//        Row(
//            modifier = Modifier.fillMaxWidth(),
//            verticalAlignment = Alignment.CenterVertically
//        ) {
//            Spacer(modifier = Modifier.size(8.dp))
//            AsyncImage(
//                model = postInfo.user.avatar?.let {
//                    val url = "${Config.ADDRESS}avatars/$it"
//                    Log.d("HomeRoute", "🟢 尝试加载头像 URL: $url")
//                    url
//                }?: run {
//                    Log.d("HomeRoute", "🔴 无服务器头像文件名，显示默认头像")
//                    R.drawable.ic_default_avatar
//                },
//                contentDescription = "发布者头像",
//                modifier = Modifier
//                    .size(30.dp)
//                    .clip(CircleShape)
//                    .background(Color.Transparent),
//                contentScale = ContentScale.Crop,
//                error = painterResource(id = R.drawable.ic_default_avatar) // 加载失败时显示默认
//            )
//            Spacer(modifier = Modifier.size(6.dp))
//            Text(
//                text = "添加评论...",
//                fontSize = 12.sp,
//                color = InstagramDarkGray
//            )
//        }
//        Spacer(modifier = Modifier.height(6.dp)) // 添加底部内边距
    //发布日期
    postInfo.createdTime?.let {
        androidx.compose.material.Text(
            text = it,
            fontSize = 10.sp,
            color = InstagramDarkGray,
            modifier = Modifier.padding(start = 8.dp)
        )
    }
}

@SuppressLint("CoroutineCreationDuringComposition")
@Composable
fun UserCommentBar(
    postViewModel: PostViewModel,
    onSendComment: () -> Unit,
    replyToComment: CommentDTO?,
    focusRequester: FocusRequester,
) {
    Divider(modifier = Modifier.fillMaxWidth(), color = InstagramLightGray)
    Row(
        modifier = Modifier.fillMaxWidth(),
        verticalAlignment = Alignment.CenterVertically
    ) {
        val commenter = SessionManager.currentUser
        // 内部状态
        var replyToCommenter by remember { mutableStateOf<UserInfo?>(null) }
        var commenterName by remember { mutableStateOf("") }
        var displayText by remember { mutableStateOf("") }


        // 发送评论逻辑
        val sendComment: () -> Unit = {
            postViewModel.caption = displayText
            onSendComment() // 调用外部传入的 onSendComment
            // 重置内部状态
            postViewModel.caption = ""
            replyToCommenter = null
            commenterName = ""
            displayText = ""
        }


        LaunchedEffect(replyToComment) {
            replyToCommenter = replyToComment?.let {
                MyRetrofitDatasource.getUserById(it.commenterId).data
            }
            commenterName = replyToCommenter?.userName ?: ""
            // 初始化时附加 "@userName：" 前缀（仅当有回复时）
            if (replyToComment != null) {
                displayText = "@${commenterName}："
                postViewModel.caption = ""
            } else {
                displayText = postViewModel.caption
            }
        }


        //发布者头像
        AsyncImage(model = commenter?.avatar?.let {
            val url = "${Config.ADDRESS}avatars/$it"
            Log.d("HomeRoute", "🟢 尝试加载头像 URL: $url")
            url
        } ?: run {
            Log.d("HomeRoute", "🔴 无服务器头像文件名，显示默认头像")
            R.drawable.ic_default_avatar
        },
            contentDescription = "发布者头像",
            modifier = Modifier
                .size(30.dp)
                .clip(CircleShape)
                .background(Color.Transparent),
            contentScale = ContentScale.Crop,
            error = painterResource(id = R.drawable.ic_default_avatar) // 加载失败时显示默认
        )


        TextField(
            value = displayText,
            onValueChange = { newValue ->
                // 处理输入：当有回复时，禁止删除 "@userName：" 前缀
                if (replyToComment != null) {
                    val prefix = "@${commenterName}："
                    if (newValue.startsWith(prefix)) {
                        displayText = newValue
                        postViewModel.caption = newValue.removePrefix(prefix)
                    }
                } else {
                    displayText = newValue
                    postViewModel.caption = newValue
                }
            },
            placeholder = {
                Text(
                    text =
                    //if (commenterName.isNotEmpty()) commenterName else
                    "添加评论...",
                    color = Color.Gray
                )
            },
            modifier = Modifier
                .weight(1f)
                .focusRequester(focusRequester),
            colors = TextFieldDefaults.textFieldColors(
                backgroundColor = Color.Transparent, // 设置背景颜色为透明
                focusedIndicatorColor = Color.Transparent, // 设置聚焦时的指示线颜色为透明
                unfocusedIndicatorColor = Color.Transparent, // 设置未聚焦时的指示线颜色为透明
            ),
            textStyle = MaterialTheme.typography.body1.copy(color = MaterialTheme.colors.onSurface), // 设置文本颜色
        )
        if (postViewModel.caption.isBlank()) {
            Image(
                painter = painterResource(id = R.drawable.emoji),
                contentDescription = null,
                modifier = Modifier
                    .size(35.dp)
                    .padding(end = 10.dp)
            )
        } else {
            Box(
                modifier = Modifier
                    .padding(end = 10.dp)
                    .size(30.dp)
                    .clip(RoundedCornerShape(15.dp))
                    .background(InstagramBlue)
                    .clickableNoRipple {
                        sendComment()
                    },
            ) {
                Image(
                    painter = painterResource(id = R.drawable.send),
                    contentDescription = null,
                    modifier = Modifier
                        .size(30.dp)
                )
            }
        }
    }
}